<?php
/**
 * 
    $coupon['use_scope']  = 0;
    $coupon['owner']      = 1;
    $coupon['is_open']    = 1;
    $coupon['is_used']    = 0;
    $coupon['type']       = 1001;
    $coupon['start_date'] = '2017-12-01';
    $coupon['end_date']   = '2017-12-31';
    $coupon['num']        = 1;
    $coupon['price']      = floatval(round(mt_rand (60, 90) / 10, 2));
    $coupon['cash']       = mt_rand (100, 200);
    $coupon['type']       = $this->roll(array(1001 => 5, 1002 => 1));

    if ($coupon['type']   == 1001) {
       $coupon['price'] = mt_rand (10, 50);
       $coupon['cash']  = mt_rand (500, 500);
    }
    model('Coupons')->createCoupons($coupon);
    model('Coupons')->bindCoupon('521c19b5-830e-4bc0-bfc9-2edb14f7f30b', 1);
 */
namespace app\common\model;

use think\Model;
use \think\Exception;
use Carbon\Carbon;
use Ramsey\Uuid\Uuid;
/**
 * 优惠券模型类
 */
class Coupons extends Model
{
    protected $table              = 'coupons';
    protected $autoWriteTimestamp = 'timestamp';
    protected $createTime         = 'created_at';
    protected $updateTime         = 'updated_at';
    protected $type               = [
        '1001' => '分享现金券',
        '1002' => '分享折扣券',
        //'2001' => '出租现金券',
        //'2002' => '出租折扣券',
        //'3001' => '现金券',
        //'3002' => '折扣券'
    ];

	/**
	 * 创建优惠券信息
	 * @param  array  $coupon    优惠券
	 * @return bollean           是否成功
	 */		
    protected function createCoupon($coupon)
    {
        $coupons                = [];
        $nums                   = isset($coupon['num']) ? $coupon['num'] : 1;
        $coupon_info            = $coupon;
        unset($coupon['num']);

        for ($i=0; $i < $nums; $i++) { 
            $coupon['number']       = isset($coupon_info['number']) ? $coupon_info['number'] : Uuid::uuid4()->toString();
            $coupons[] = $coupon;
        }
        $this->allowField(true)->saveAll($coupons);

    	return $coupons;
    }

    public function createCoupons($coupons_info)
    {
        if (!is_array($coupons_info)) {
            throw new Exception("Coupon information for array", 1);
        }
        if (key($coupons_info) === 0) {
            foreach ($coupons_info as $coupon_info) {
                if (!is_array($coupon_info) || key($coupon_info) === 0) {
                    throw new Exception("Coupon information for array", 1);
                }
                $this->createCoupon($coupon_info);
            }
        }else{
            $this->createCoupon($coupons_info);
        }
    }

    public function getCoupons($where, $page = 0, $order = 'id desc')
    {
        return $this->all(function($query) use ($where, $page, $order) {
                $query->where($where)->page($page)->order($order);
            });
    }

    /**
     * 获取有效的优惠券
     * @param  [type]  $where [description]
     * @param  integer $page  [description]
     * @param  string  $order [description]
     * @return [type]         [description]
     */
    public function getValidCoupons($where, $page = 0, $order = 'id desc')
    {
        $today               = Carbon::now()->toDateString();
        $where['end_date']   = ['EGT', $today];
        $where['start_date'] = ['ELT', $today];

        return $this->getCoupons($where, $page, $order);
    }

    public function transferCouponType($type)
    {
        return $this->type[$type];
    }

    /**
     * 获取优惠券信息
     * @param  [type] $coupon_no [description]
     * @return [type]            [description]
     */
    public function getCouponInfo($coupon_no)
    {
    	return $this->get(['number' => $coupon_no]);
    }

    /**
     * 关闭优惠券
     * @param  [type] $coupon_no [description]
     * @return [type]            [description]
     */
    public function closeCoupon($coupon_no)
    {
    	return $this->setCouponOpenStatus($coupon_no, false);
    }

    /**
     * 开放优惠券
     * @param  [type] $coupon_no [description]
     * @return [type]            [description]
     */
    public function openCoupon($coupon_no)
    {
        return $this->setCouponOpenStatus($coupon_no);
    }

    /**
     * 绑定优惠券到用户
     * @param  [type] $coupon_no [description]
     * @param  [type] $owner     [description]
     * @return [type]            [description]
     */
    public function bindCoupon($coupon_no, $owner)
    {
        if (!model('Users')->getUserInfo(['id' => $owner])) {
            throw new Exception("Target member does not exist", 1);            
        }

        $coupon = $this->get(['number' => $coupon_no, 'owner' => 0, 'is_used' => 0]);
        if ($coupon) {
            $coupon->owner        = $owner;
            $coupon->is_open      = 1;
            $coupon->release_date = Carbon::now()->toDateString();
            $coupon->save();
            return true;
        }else{
            return false;
        } 
    }

    /**
     * 转让优惠券
     * @param  [type] $owner     [description]
     * @param  [type] $coupon_no [description]
     * @param  [type] $to_owner  [description]
     * @return [type]            [description]
     */
    public function transferCoupon($owner, $coupon_no, $to_owner)
    {
        if (!model('Users')->getUserInfo(['id' => $to_owner])) {
            throw new Exception("Target member does not exist", 1);            
        }

        $coupon = $this->get(['number' => $coupon_no, 'owner' => $owner, 'is_used' => 0]);
        if ($coupon) {
            $coupon->owner = $to_owner;
            $coupon->save();
            return true;
        }else{
            return false;
        }        
    }

    /**
     * 删除优惠券
     * @param  [type]  $coupon_no [description]
     * @param  boolean $force     是否强制删除
     * @return [type]             [description]
     */
    public function delCoupons($coupon_no, $force = false)
    {
        $this->couponOnToArray($coupon_no);

        $this->where(['number' => ['in', $coupon_no]]);

        if (!$force) {
            $this->where(['owner' => 'null']);
        }
        $this->delete();
    }

    protected function setCouponOpenStatus($coupon_no, $is_open = true)
    {
        $this->couponOnToArray($coupon_no);

        $is_open = $is_open ? 1 : 0;

        $this->updateCoupons(['number' => ['in', $coupon_no]], ['is_open' => $is_open]);
    }

    public function updateCoupons($where, $data)
    {
        self::where($where)->update($data);
    }

    public function setCouponUseStatus($coupon_no, $is_used = true)
    {
        $this->couponOnToArray($coupon_no);

        $is_used = $is_used ? 1 : 0;

        $this->updateCoupons(['number' => ['in', $coupon_no]], ['is_used' => $is_used]);
    }

    private function couponOnToArray(&$coupon_no, $types = ['string', 'array'])
    {
        if (!$coupon_no) {
            throw new Exception("Coupon_no not be null!", 1);        
        }else{
            $type = gettype($coupon_no);
            if(!in_array($type, $types)) {
                throw new Exception("Coupon_no format error!" . $type, 2); 
            }
            if (is_string($coupon_no)) {
                $coupon_no = explode(',', $coupon_no);
            }
        }
    }
}
